package jroguelike.main.ai;

import jroguelike.main.ArtificialIntelligence;
import jroguelike.main.Creature;
import jroguelike.main.RLMap;
import jroguelike.main.RLWindow;

/**
 * Created by IntelliJ IDEA.
 * User: aimozg
 * Date: 06.08.11
 * Time: 15:36
 */
public abstract class AbstractAi extends ArtificialIntelligence {

	public int wanderDirection = -1;

	@Override
	protected void cloneTo(ArtificialIntelligence other) {
		super.cloneTo(other);
		AbstractAi xother = (AbstractAi) other;
		xother.wanderDirection = wanderDirection;
	}

	protected boolean aiMeleeAttack(Creature target) {
		return me.world.tryActionMeleeAttack(me, target);
	}

	protected boolean aiMoveTo(int txy) {
		// TODO pathfinding
		RLMap map = me.map();
		int x = me.x();
		int y = me.y();
		int tx = map.x(txy);
		int ty = map.y(txy);
		int dx = (tx == x) ? 0 : ((tx > x) ? +1 : -1);
		int dy = (ty == y) ? 0 : ((ty > y) ? +1 : -1);
		if (me.world.tryActionStep(me, dx, dy)) return true;
		if (me.world.rng.nextBoolean()) {
			// step x first
			if (dy != 0 && me.world.tryActionStep(me, dx, 0)) return true;
			if (dx != 0 && me.world.tryActionStep(me, 0, dy)) return true;
		} else {
			// step y first
			if (dy != 0 && me.world.tryActionStep(me, 0, dy)) return true;
			if (dx != 0 && me.world.tryActionStep(me, dx, 0)) return true;
		}
		// cannot move directly
		return false;
	}

	protected boolean aiWander() {
		if (wanderDirection == -1 || me.world.rng.nextInt(10) == 0) wanderDirection = me.world.rng.nextInt(8);
		return me.world.tryActionStep(me, RLWindow.directionDxs[wanderDirection], RLWindow.directionDys[wanderDirection]);
	}
}
